<!--

/**
* selectRecordFromSearch.html: select record from popup for setting record pointer fields
*
* @package     Heurist academic knowledge management system
* @link        http://HeuristNetwork.org
* @copyright   (C) 2005-2014 University of Sydney
* @author      Artem Osmakov   <artem.osmakov@sydney.edu.au>
* @author      Ian Johnson     <ian.johnson@sydney.edu.au>
* @author      Tom Murtagh, Kim Jackson, Stephen White
* @license     http://www.gnu.org/licenses/gpl-3.0.txt GNU License 3.0
* @version     3.2
*/

/*
* Licensed under the GNU License, Version 3.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at http://www.gnu.org/licenses/gpl-3.0.txt
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied
* See the License for the specific language governing permissions and limitations under the License.
*/


-->

<html>
    <head>
        <link rel=stylesheet href="../../common/css/global.css">
        <link rel=stylesheet href="../../common/css/edit.css">
        <title>Select record ...</title>
        <style>
            /* sets position of the grey section relative to top of popup - alter in sync with position of top of results*/
            #search {height: 120px;left: 0;margin-bottom: 10px;position: relative;top: 0;}
            /* sets position of the list of results relative to top of popup */
            #results {bottom: 26px;display: block;left: 0;overflow-y: auto;position: absolute;right: 0;top: 130px;}
            body.popup {padding: 0 !important; overflow: hidden;}
            .result_row {padding:1ex 10px 0 10px;}
            .result_row .id{width:10ex;display:inline-block;text-align: right;color:#999;}
            .result_row img{margin:0 8px;}
            div.result_row:hover{cursor: pointer;}
        </style>
    </head>
    <body class="popup" width="650">
        <script src="../../common/js/utilsLoad.js"></script>
        <script>
            if (window == top) { // core HEURIST object definitions (dynamically generated)
                top.HEURIST.loadScript(top.HEURIST.basePath +"common/php/loadCommonInfo.php");
            }
        </script>

        <form onSubmit="this.submit(); return false;">
            <div style="margin-top: 0px; margin-left: 10px; margin-bottom: 0px;" >
            </div>
            <div id="search" class="banner" style="top:0;">

                <table border=0 cellspacing=0 cellpadding=0 class=expander style="margin-bottom: 1em;">
                    <tr>
                        <td style="width: 40px; text-align: right;"><b>Find:</b>&nbsp;</td>
                        <td style="padding: 2px 5px 5px 5px;">
                            <div style="width: 98%;" class="searchInput">
                                <div><input autocomplete=off type=text name="q" id="q"
                                    onChange="top.HEURIST.util.setDisplayPreference('record-search-string', this.value);"
                                    style="padding: 1px 18px 1px 2px; margin: 6px; width: 100%;"></div>
                                <div id="help-div" class="help prompt"
                                    style="width: 300px; margin-left: 20px; font-size: smaller;">
                                    Select below or search on title here.
                                    [enter] or <img src="../../common/images/magglass_12x11.gif"
                                        onClick="document.forms[0].submit()" style="vertical-align: middle;"> to search</div>
                            </div>
                        </td>
                        <td style="width: 1px; vertical-align: middle;">
                            <div style="overflow: visible; width: 1px;">
                                <img src="../../common/images/magglass_15x14.gif"
                                    style="position: relative; cursor: pointer; z-index: 1; top:1px; left: -22px;"
                                    onclick="document.forms[0].submit()" title="Search records">
                            </div>
                            <!-- Produces mis-aligned and superfluous Find button even though marked as display:none
                            <input type=submit value=Find style="display: none; font-weight: bold; padding: 0 1ex; margin-right: 1ex;" >
                            -->
                        </td>
                        <td style="width: 120px;" title="Restrict search to this record type">
                            in <select id="t" name="t" style="width: 90%;"
                            onChange="document.forms[0].submit('record-search-type')"></select>
                        </td>
                        <td style="width: 80px; padding: 10 5px;">
                            <div class="radio" style="white-space:nowrap;">
                                <label for=r-all>
                                    <input type=radio name=r id=r-all value=all
                                    onChange="document.forms[0].submit('r-all')"> all records
                                </label>
                            </div>
                            <div class="radio" style="white-space:nowrap;">
                                <label for=r-recent-search>
                                    <input type=radio name=r id=r-recent-search value=recent-search
                                    onChange="document.forms[0].submit('r-recent-search')"> recently selected
                                </label>
                            </div>
                            <div class="radio" style="white-space:nowrap;">
                                <label for=r-recent>
                                    <input type=radio name=r id=r-recent value=recent
                                    onChange="document.forms[0].submit('r-recent')"> recently added
                                </label>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="5" rowspan="1" style="padding-top: 0px; padding-left: 30px;">
                            <b>or</b> &nbsp;&nbsp;&nbsp;
                            <a href="#" style="border: 3px; border-style: outset; border-color: black;"
                            title="Create and edit a new record, which will become the target of the pointer field"
                            onClick=" return addRecord();">
                            &nbsp;&nbsp;<img src="../../common/images/add-record-small.png" style="border: 1px;"/>
                            &nbsp;&nbsp;<b>Create a new record</b></a>
                            &nbsp;&nbsp;<i>Record becomes target of current pointer field</i>
                        </td>
                    </tr>
                    <tr>
                        <td>&nbsp;</td>
                    </tr>
                </table>

            </div>
            <!--   <div id=results-container class=expander style="overflow: hidden;">-->
            <div id=results></div>
            <!--   </div>-->
        </form>

        <script language="JavaScript">
            // parse the parameter line for input parameters t = constrained type list and q = title of the record pointed to.
            window.HEURIST.parameters = top.HEURIST.parseParams(window.location.search);

            // check for type constraints
            var rectype = window.HEURIST.parameters["t"];
            var rtName;
            if (rectype) {
                var rectypes = {};
                var recTypeName = "";
                if (rectype.search(",") != -1) {//seems like we have multiple type constraint, test that it is well formed
                    var temp = rectype.split(",");
                    for (var i=0; i<temp.length; i++) {
                        if (temp[i].search(/\D/) == -1) {
                            rectypes[temp[i]] = 1;// add entry to lookup as 1 for truthy
                            rtName = top.HEURIST.rectypes.names[temp[i]];
                            if(!top.HEURIST.util.isnull(rtName)){
                                recTypeName += rtName.toLowerCase() + ",";
                            }
                        }
                    }
                    recTypeName = recTypeName.slice(0,-1); // remove the last comma
                    delete temp;
                }else if (rectype.search(/\D/) == -1 && rectype.search(/\d/) != -1) {
                    rectypes[rectype] = 1;// add entry to lookup as 1 for truthy
                    rtName = top.HEURIST.rectypes.names[rectype];
                    if(!top.HEURIST.util.isnull(rtName)){
                        recTypeName = rtName.toLowerCase();
                    }
                }else{
                    rectypes = null;
                }
            }

            /* If a rectype has been chosen then set a custom title -- need to do before onload so the popup code will catch it */
            if (recTypeName) {
                document.title = "Select / create: " + recTypeName;
            }

            /*
            *
            */
            function addRecord(){

                var recTypeId = document.getElementById('t').value;

                var title = "Add new record "+top.HEURIST.util.getRectypeIconAndName(recTypeId);

                var forrectype = top.HEURIST.util.getRectypeIconAndName(window.HEURIST.parameters["target_recordtype"]);
                if(forrectype){
                    title = title + " for " + forrectype;
                }


                var _db = (window.HEURIST && window.HEURIST.parameters && window.HEURIST.parameters.db ? window.HEURIST.parameters.db :
                    (top.HEURIST.parameters.db?top.HEURIST.parameters.db:
                        (top.HEURIST.database.name? top.HEURIST.database.name:'')));

                top.HEURIST.util.popupURL(window, top.HEURIST.basePath +'records/add/formAddRecordPopup.html?rectype='+
                    recTypeId+
                    '&title='+document.getElementById('q').value+	// q is a string to match against rectitle so let's start with this in the title field
                    '&db='+ _db,
                    {	title: title,
                        callback: function(title, bd, bibID) {
                            if (bibID) {
                                window.close(bibID, title);
                            } else {
                                document.forms[0].submit();
                            }
                        }
                });
                return false;
            }

            // search callback which fills the result area with a line for each record in the result set
            function notifyResults(results) {
                var resultsDiv = document.getElementById("results");
                var records = eval(results.responseText).records;	//saw TODO: this need to be more secure and standardised

                var recordDiv;
                var record;
                var bibID, img, title;

                resultsDiv.innerHTML = "";
                for (var i=0; i < records.length; ++i) {
                    record = records[i];

                    recordDiv = resultsDiv.appendChild(document.createElement("div"));
                    recordDiv.className = "result_row";

                    bibID = recordDiv.appendChild(document.createElement("span"));
                    bibID.appendChild(document.createTextNode(record[0]));
                    bibID.className = "id";

                    img = recordDiv.appendChild(document.createElement("img"));
                    img.src = top.HEURIST.basePath + "common/images/16x16.gif";
                    img.style.backgroundImage = "url("+ top.HEURIST.iconBaseURL + (record[3]? record[3] : "blank") + ".png)";

                    title = recordDiv.appendChild(document.createElement("span"));
                    title.appendChild(document.createTextNode(record[1]));
                    title.title = record[1];
                    title.className = "title";


                    //select record and close
                    top.HEURIST.registerEvent(recordDiv, "click", function(bibID, bibTitle, recType) {
                        return function() {

                            //save last selected
                            var lastSelected = top.HEURIST.util.getDisplayPreference("record-search-last");
                            lastSelected = (lastSelected==="")?[]:lastSelected.split(",",50);
                            var k = lastSelected.indexOf(bibID);
                            if(k<0){
                                if(lastSelected.length>49) {	// if we have hit the max, remove bottom item
                                    lastSelected.shift();
                                }
                                lastSelected.push(bibID);	//put recID on top of list
                            } else if (k<49) {
                                lastSelected.splice(k,1);	//remove recID
                                lastSelected.push(bibID);	// and put it on top of list
                            }

                            top.HEURIST.util.setDisplayPreference("record-search-last", lastSelected.join(","));

                            ///close and window and sent result
                            window.close(bibID, bibTitle);
                        }
                        }(record[0], record[1], record[3]));
                }

                if (records.length == 0) {
                    resultsDiv.innerHTML = "<b style='padding: 40px 40px;'><p/>No records matched search. Create and attach a new record with button above</b>";
                }

                document.body.cursor = "";
            }

            document.forms[0].submit = function(txt) {
                // Make an AJAX request for the search results.  If no search specified, default to RECENT entries.
                var q = document.forms[0].elements["q"].value;
                var t = document.forms[0].elements["t"].value;
                q = q.replace(/^\s*/,"");
                q = q.replace(/\s*$/,"");
                t = t.replace(/^\s*/,"");
                t = t.replace(/\s*$/,"");
                if (t == "0") t = "";

                switch(txt){
                    case "r-recent-search":
                    case "r-recent":
                    case "r-all":
                        if (top.HEURIST.util.getDisplayPreference('record-search-scope') != txt){
                            top.HEURIST.util.setDisplayPreference('record-search-scope', txt);
                        }
                        break;
                    case "record-search-type":
                        if (top.HEURIST.util.getDisplayPreference('record-search-type') != t){
                            top.HEURIST.util.setDisplayPreference('record-search-type', t);
                        }
                        break;
                    default:
                }

                if(q!=""){
                    q = "\""+q+"\"";
                }

                q += (t? ((q?" ":"")+"type:"+parseInt(t)) : "");

                if(document.getElementById("r-recent-search").checked){
                    //find recent search results
                    var lastSelected = top.HEURIST.util.getDisplayPreference("record-search-last");
                    q += (q?" ":"") + " ids:"+lastSelected;
                }

                // saw TODO modify for multi constraints set
                var query = "q=" + encodeURIComponent(q);

                if (document.getElementById("r-recent").checked ) {
                    query += "&r=recent";
                }

                if (top.HEURIST.parameters.db) {
                    query += "&db=" + top.HEURIST.parameters.db;
                }else if (top.HEURIST.database.name) {
                    query += "&db=" + top.HEURIST.database.name;
                }

                document.body.cursor = "wait";

                var resultsDiv = document.getElementById("results");
                resultsDiv.innerHTML = "<i style='padding: 1ex;'>Searching ...</i>";

                top.HEURIST.util.sendRequest(top.HEURIST.baseURL + "records/pointer/getRecordListForSearch.php", notifyResults, query);

                return false;
            }

            /* FLAGRANT abuse of the onsubmit function, but otherwise hitting return in the field submits the entire page */
            document.forms[0].onsubmit = function() { document.forms[0].submit(); return false; };


            function initPage() {
                //get the passed in title
                var qVal = window.HEURIST.parameters["q"];
                var existingRecord = (qVal?true:false);
                var lastSearchString = top.HEURIST.util.getDisplayPreference("record-search-string");
                var searchScope = top.HEURIST.util.getDisplayPreference("record-search-scope");
                var lastSelected = top.HEURIST.util.getDisplayPreference("record-search-last");
                var lastSearchType = window.HEURIST.parameters["deft"]
                ?window.HEURIST.parameters["deft"]
                :top.HEURIST.util.getDisplayPreference("record-search-type");
                var rectypeIDList = [];
                //set focus
                window.setTimeout(function() {
                    document.forms[0].elements["q"].focus();
                    document.forms[0].elements["q"].select();
                    },200);

                document.body.className = document.body.className + ' help-'+top.HEURIST.util.getDisplayPreference("help")+' ';

                //get last selected rectype
                var initialType = top.HEURIST.util.getDisplayPreference("record-search-type");
                if (rectypes && !rectypes[initialType]) {//if preferred is not in constrained list choose first rectype
                    for (var type in rectypes) {	// careful! this only runs once to get and then breaks out.
                        initialType = type;
                        break;
                    }
                }

                //create rectype selector and set intial selection
                var tElt = document.getElementById("t");
                tElt.selectedIndex = 0;

                if (!rectypes) {// unconstrained pointer
                    tElt.options[tElt.options.length] = new Option("Any record type", "");
                    var isNotFound = true;
                    if(!lastSearchType){
                        lastSearchType = top.HEURIST.magicNumbers['RT_AGGREGATION'];
                    }

                    // rectypes displayed in Groups by group display order then by display order within group
                    for (index in top.HEURIST.rectypes.groups){
                        if (index == "groupIDToIndex" ||
                            top.HEURIST.rectypes.groups[index].showTypes.length < 1) {
                            continue;
                        }
                        var grp = document.createElement("optgroup");
                        grp.label = top.HEURIST.rectypes.groups[index].name;
                        tElt.appendChild(grp);
                        for (var recTypeIDIndex in top.HEURIST.rectypes.groups[index].showTypes) {
                            var recTypeID = top.HEURIST.rectypes.groups[index].showTypes[recTypeIDIndex];
                            var name = top.HEURIST.rectypes.names[recTypeID];
                            if(!top.HEURIST.util.isnull(name)){
                                tElt.appendChild(new Option(name, recTypeID));

                                if(recTypeID == lastSearchType){
                                    tElt.selectedIndex = tElt.options.length-1;
                                    isNotFound = false;
                                }
                            }
                        }
                    }

                    if(isNotFound){
                        lastSearchType = null;
                    }

                    if (tElt.rectypes){
                        delete tElt.rectypes;
                    }
                }else{ // pointer constrained to rectypes - ignore showTypes
                    var isNotFound = true;
                    for (var rectypeID in rectypes) {
                        var name = top.HEURIST.rectypes.names[rectypeID];
                        if(!top.HEURIST.util.isnull(name))
                        {
                            tElt.appendChild( new Option(name, rectypeID));
                            if (rectypeID == initialType) {// select inital type
                                tElt.selectedIndex = tElt.options.length-1;
                            }
                            if(rectypeID == lastSearchType){
                                isNotFound = false;
                            }
                            rectypeIDList.push(rectypeID);
                        }
                    }
                    if(isNotFound){
                        lastSearchType = null;
                    }
                    tElt.rectypes = rectypeIDList.join();
                }

                //initialise form
                if(existingRecord)
                {
                    document.forms[0].elements["q"].value = qVal;
                    document.getElementById("r-all").checked = true;
                }else{//new record
                    if(lastSearchType){
                        document.getElementById("t").value = lastSearchType;
                    }
                    document.getElementById(searchScope).checked = true;
                }
                document.forms[0].submit();

                /*				var intervalID = setInterval(function() {
                try {
                if (document.getElementById("q")) {
                document.getElementById("q").focus();
                clearInterval(intervalID);
                }
                } catch (e) { }
                }, 0); */
            }

            top.HEURIST.registerEvent(window, "load", initPage);
        </script>
    </body>
</html>
